<template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-input
            placeholder="搜索用户名"
            style="width: 160px; height: 36px"
            @search="onSearch"
            v-model="searchDetail"
          />

          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toSearch"
            :disabled="!isAuth(['ROOT', 'USER:SELECT'])"
          >
            查询
          </a-button>
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toAdd"
            v-if="isAuth(['ROOT', 'USER:INSERT'])"
          >
            新增
          </a-button>
          <a-popconfirm
            title="是否进行批量删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm2"
            @cancel="cancel2"
            :disabled="!isAuth(['ROOT', 'USER:DELETE'])"
          >
            <a-button
              type="danger"
              style="margin-left: 10px; width: 98px; height: 36px"
              v-if="isAuth(['ROOT', 'USER:DELETE'])"
            >
              批量删除
            </a-button>
          </a-popconfirm>
        </div>
        <div class="main_table">
          <a-spin
            size="large"
            v-show="loadingVisible"
            style="loading_icon"
            tip="正在加载中"
          ></a-spin>
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-table
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            @change="handleTableChange"
            rowKey="id"
          >
            <!-- 作用域插槽 text 本身是每一列的所有属性 但是 column的配置是 dataIndex 是avaurl 所以text 就变成了每一类的avarurl -->
            <img
              style="width: 50px; height: 50px; border-radius: 50%"
              slot="pic"
              slot-scope="text"
              :src="text"
            />
            <span slot="action" slot-scope="text, record">
              <a
                v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                @click="modifyItem(record)"
                :class="record.id == '0' ? 'rootColor' : ''"
                >修改</a
              >
              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'USER:UPDATE'])"
              />
              <a-popconfirm
                :disabled="!isAuth(['ROOT', 'USER:DELETE'])"
                title="请确定是否删除该用户信息"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteItem(record)"
                @cancel="cancel(record)"
              >
                <a
                  v-if="isAuth(['ROOT', 'USER:DELETE'])"
                  href="#"
                  :class="
                    is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                  "
                  >删除
                </a>
              </a-popconfirm>
              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'USER:DELETE'])"
              />
              <a-popconfirm
                v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                title="请确定是否重置密码(默认为888888888)"
                ok-text="确定"
                cancel-text="取消"
                @confirm="resetPassword(record.id)"
                @cancel="cancel(record)"
              >
                <a
                  href="#"
                  :class="
                    is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                  "
                >
                  重置
                </a>
              </a-popconfirm>
              <!-- 如果权限中包含Teacher 说明是老师 可以根据 -->
              <div class="controller" v-if="record.roles.includes('teacher')">
                <a-divider
                  type="vertical"
                  v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                />
                <a
                  v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                  @click="managerTeacher(record)"
                  href="#"
                  :class="
                    is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                  "
                  >教师管理</a
                >
              </div>
            </span>
          </a-table>
        </div>
      </div>
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getRoleMessage"
    ></add-or-update>
  </div>
</template>
<script>
import AddOrUpdate from "../components/user-add-or-update.vue";
export default {
  components: {
    AddOrUpdate,
  },
  data() {
    return {
      selectedRowKeys: [], // Check here to configure the default column
      loadingVisible: true,
      // 判断是否是超管
      is_admin: false,
      //删除中多选中的id列表
      idList: [],
      // 搜索框的教师名字
      searchTeacher: "",
      // 搜索框内容
      searchDetail: "",
      // 静态模态的出现
      addOrUpdateVisible: false,
      // 列名
      columns: [
        // title:列名; dataIndex: 对应数据源中的键值(kay)
        {
          title: "头像",
          dataIndex: "avatarUrl",
          fixed: "left",
          key: "pic",
          scopedSlots: { customRender: "pic" },
        },
        {
          title: "姓名",
          dataIndex: "name",
        },

        {
          title: "用户名",
          dataIndex: "username",
        },

        {
          title: "性别",
          dataIndex: "sex",
        },
        {
          title: "电子邮箱",
          dataIndex: "email",
        },
        {
          title: "电话号码",
          dataIndex: "tel",
        },
        {
          title: "操作",

          key: "action",
          scopedSlots: { customRender: "action" },
        },
      ],
      // 数据源
      data: [
        //  键值key 对应列名, key为Vue 需要key 可以忽略
      ],
      pagination: {
        position: "bottom",
        pageSize: 10,
        current: 1,
        total: 0,
        pageSize: 10,
        pageSizeOptions: ["10", "15", "20", "25"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
      },
      //   表头的配置条件
      sortedInfo: null,
    };
  },
  created() {
    // this.getRoleMessage();
    // 分页查询数据
    this.searchRole();
    // this.getUserMessage();
    this.getCurrentUser();
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed:123 ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let ids = [];
      selectedRowKeys.forEach((item) => {
        ids.push(item);
      });
      this.idList = ids;
    },

    // 获取当前用户信息 判断是否是超管
    async getCurrentUser() {
      const { data: res } = await this.$http.get("/admin/currentuser");
      if (res.data.roles.includes("admin")) {
        this.is_admin = true;
      }
    },
    // 批量删除按钮 确认弹框
    confirm2(e) {
      this.mutiDelete();
    },
    // 批量删除按钮 取消弹框
    cancel2() {},
    cancel() {},
    // 批量删除
    async mutiDelete() {
      this.loadingVisible = true;
      const { data: res } = await this.$http.delete("/admin/users", {
        data: {
          ids: this.idList,
        },
      });
      if (res.code == 200) {
        this.idList.forEach((target) => {
          this.selectedRowKeys = this.selectedRowKeys.filter((item) => {
            return item != target;
          });
        });
        this.idList = this.selectedRowKeys;
        this.pagination.current = 1;
        this.common.notify("success", "删除成功");
        this.getRoleMessage();
      } else {
        this.getRoleMessage();
        this.common.notify("warning", "删除失败", "请重新选择");
      }
    },
    managerTeacher(record) {
      if (record.id != 0 || this.is_admin == true) {
        this.$router.push({
          name: "teacherManager",
          params: { record },
        });
      } else {
        // this.$message.warning("没有该权限");
        this.common.notify("warning", "暂无权限", "只有超管自己才能修改该用户");
      }
    },
    modifyItem(record) {
      this.loadingVisible = true;
      if (record.id != 0 || this.is_admin == true) {
        //可以修改 id 为0的超管 但是要考虑是否是本人 只有超管自己 可以修改超管
        this.addOrUpdateVisible = true;
        this.$nextTick(() => {
          this.$refs.addOrUpdate.update(record);
        });
      } else {
        this.common.notify("warning", "暂无权限", "只有超管自己才能修改该用户");
      }
    },
    async resetPassword(id) {
      console.log("record", id);
      this.loadingVisible = true;
      if (id != 0 || this.is_admin == true) {
        //如果id 为0 但是是本人操作 则可以允许访问
        const { data: res } = await this.$http.put(`/admin/repass/${id}`);
        if (res.code == 200) {
          this.common.notify("success", "重置成功");
          this.loadingVisible = false;
        }
      } else {
        this.common.notify("warning", "暂无权限", "只有超管自己才能修改该用户");
      }
    },
    // 查询用户
    async toSearch() {
      this.loadingVisible = true;
      if (this.searchDetail == "") {
        this.getRoleMessage();
      } else {
        const { data: res } = await this.$http.get(
          `/admin/users?username=${this.searchDetail}`
        );
        this.data = res.data.records;
        this.loadingVisible = false;
      }
    },
    toAdd() {
      this.loadingVisible = true;
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init();
        // 清空表单 发送请求 获取表单项的部分选择数据.
      });
    },
    async deleteItem(item) {
      this.loadingVisible = true;
      if (item.id != 0) {
        let ids = [item.id];
        const { data: res } = await this.$http.delete("/admin/users", {
          data: {
            ids: ids,
          },
        });
        if (res.code == 200) {
          // this.$message.success("删除成功");
          this.selectedRowKeys = this.selectedRowKeys.filter((target) => {
            return target != item.id;
          });
          this.idList = this.selectedRowKeys;
          this.pagination.current = 1;
          this.common.notify("success", "删除成功");
          this.getRoleMessage();
        }
      }
    },
    // 分页点击切换
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;

      let that = this;
      that.sortedInfo = sorter;
      const pager = { ...that.pagination };
      pager.current = pagination.current;
      that.pagination = pager;
      this.searchRole();
    },
    // 查询按钮
    onSearch(value) {},
    // 分页查询
    async getRoleMessage(val) {
      this.searchRole();
    },
    // 分页查询显示
    async searchRole() {
      // `/admin/users?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      const { data: res } = await this.$http.get(
        `/admin/users?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      );
      //   必须要是 数字型的
      console.log(res.code);
      this.loadingVisible = false;
      this.pagination.total = Number(res.data.total);

      let tmpdata = res.data.records;
      tmpdata.forEach((item) => {
        if (item.sex == 0) {
          item.sex = "男";
        } else {
          item.sex = "女";
        }
        this.data = tmpdata;
      });
      this.data = res.data.records;
    },
  },
  computed: {
    //   表格选中的配置项
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          let ids = [];
          selectedRows.forEach((item) => {
            ids.push(item.id);
          });
          this.idList = ids;
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === "Disabled User", // Column configuration not to be checked
            name: record.name,
          },
        }),
      };
    },
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  // overflow: scroll;
  padding: 35px 75px;
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    // overflow: scroll
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
.rootColor {
  color: #eee;
}
/deep/ .ant-table table {
  text-align: center;
}
/deep/ .ant-table-thead > tr > th {
  text-align: center;
}
.controller {
  display: inline;
}
/deep/ .ant-spin-spinning {
  z-index: 100;
  position: absolute;
  top: 50%;
  left: 55%;
}
</style>